import { mongo } from '#nuxt-mongodb'
import { ObjectId } from 'mongodb';
import jwt from 'jsonwebtoken';

//查询用户
interface selectUserMes{
    phone:string,
    password:string
}

//jwt密钥
const secretKey = 'chentianyu';

export default defineEventHandler(async(event:any)=>{
    //传入的值
    const {phone,password}:selectUserMes = await readBody(event)
    const db = mongo.db()
    console.log('phone:',phone)
    try {
        // 执行查询并转换游标为数组(需要输入的用户名和密码能查询到)
        const result = await db.collection('user').findOne({account:phone,password:password})
        // console.log('result:',result)
        if (result) {
            const token = jwt.sign({account:phone,password:password},secretKey,{expiresIn:'1h'})
            return {
                status: 200,
                data: result,
                token: token
            }
          } else {
            return {
                status: 404,
                data: "user is not found",
            }
          }
    } catch (error:any) {
        // 错误处理，返回错误信息
        return JSON.stringify({
            status: 500,
            message: 'Failed to retrieve data',
            error: error.message
        })
    }
})